#include "GMFramework.h"
#include <string.h>


namespace app
{

GMFramework::GMFramework( HINSTANCE hInst, WNDPROC winproc )
{
	m_running = false;
	meWindows = 0;
	meFilestream = 0;

	meWindows = new app::GMWindows;

	initialize();

	if( meWindows )
	{
		meWindows->hInstance( hInst );
		meWindows->wndproc( winproc ? winproc : default_winproc );

		m_running = meWindows->initialize();
	}
}


GMFramework::~GMFramework( void )
{
	destroy();
}


bool GMFramework::initialize( void )
{	
	if( !load_app() )
	{
		meWindows->title( "dummy" );
		meWindows->pos( 0x80000000, 0x80000000 );
		meWindows->size( 0x80000000, 0x80000000 );
	}

	return true;
}


void GMFramework::destroy( void )
{
	if( meFilestream )
	{
		delete meFilestream;
		meFilestream = 0;
	}

	if( meWindows )
	{
		delete meWindows;
		meWindows = 0;
	}
}


bool GMFramework::load_app( void )
{
	meFilestream = new io::GMFileStream;


	if( meFilestream )
	{
		if( meFilestream->open( "app.ini", "r" ) )
		{
			read_app_data();


			meFilestream->close();

			if( meFilestream )
			{
				delete meFilestream;
				meFilestream = 0;
			}


			return true;
		}
	}

	return false;
}


void GMFramework::read_app_data( void )
{
	const int buf_size = 256;
	const int temp_buf_size = 128;

	char buffer[buf_size];
	char temp[temp_buf_size];
	int x, y;
	

	while( 1 )
	{	
		memset( buffer, 0, sizeof( buffer ) );
		meFilestream->read_line( buffer, buf_size );

		if( strstr( buffer, "title" ) )
		{
			char str[temp_buf_size];

			memset( temp, 0, sizeof( temp ) );
			memset( str, 0, sizeof( str ) );

			sscanf_s( buffer, "%s\t%s", temp, sizeof( temp ), str, sizeof( str ) );

			meWindows->title( str );
		}
		else if( strstr( buffer, "pos" ) )
		{
			x = y = 0;
			memset( temp, 0, sizeof( temp ) );

			sscanf_s( buffer, "%s\t%d %d", temp, sizeof( temp ), &x, &y );

			meWindows->pos( x, y );
		}
		else if( strstr( buffer, "size" ) )
		{
			x = y = 0;
			memset( temp, 0, sizeof( temp ) );

			sscanf_s( buffer, "%s\t%d %d", temp, sizeof( temp ), &x, &y );

			meWindows->size( x, y );
		}
		else if( strstr( buffer, "<end>" ) )
		{
			break;
		}
	}
}


LRESULT CALLBACK GMFramework::default_winproc( HWND hWnd, unsigned int unMessage, WPARAM wParam, LPARAM lParam )
{
	switch( unMessage )
	{
	case WM_DESTROY :
		{
			PostQuitMessage( 0 );
		}
		return 0;
	}

	return ( DefWindowProc( hWnd, unMessage, wParam, lParam ) );
}

};